/**
 * 
 */
package com.tech.freak.pyp.data;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;

import com.tech.freak.pyp.R;
import com.tech.freak.pyp.Utils;
import com.tech.freak.pyp.data.PicoyPlaca.PYP;
import com.tech.freak.pyp.rest.RequestMethod;
import com.tech.freak.pyp.rest.RestClient;

/**
 * @author julian
 *
 */
public class SyncManager extends IntentService {

	private static final String TAG ="SyncManager";
	
	public SyncManager() {
		super("SyncManager");
		Log.i(TAG,"SyncManager");
	}
	
	public SyncManager(String name) {
		super(name);
		Log.i(TAG,"SyncManager: "+name );
	}

	/* (non-Javadoc)
	 * @see android.app.IntentService#onHandleIntent(android.content.Intent)
	 */
	@Override
	protected void onHandleIntent(Intent intent) {
		RestClient client = new RestClient(getString(R.string.update_pyp_url));
		
		try {
			client.Execute(RequestMethod.GET);
			
			switch (client.getResponseCode()) {
			case 200:
				JSONObject pyp = new JSONObject(client.getResponse());
				Log.i(TAG, "Object received: " + pyp.toString());
				
				syncDB(pyp);
				//Send broadcast with success 
				sendBroadcast(new Intent(Utils.UPDATE_SUCCESS));
				break;

			default:
				throw new Exception( "Error while Updating pYP");
			}
		} catch (Exception e) {
			Log.e(TAG, "Error while Updating pYP", e);
			//Send broadcast with Error 
			sendBroadcast(new Intent(Utils.UPDATE_ERROR));
		}
		

	}

	private void syncDB(JSONObject pyps) throws Exception{
		
		ContentResolver cr = getContentResolver();
		Cursor c = Utils.getPypsFromDB(cr);
		
		if(c != null){
			try{
				//Cycle through all items on DB
				if(c.moveToFirst()){
					do{
						String city = c.getString(c.getColumnIndex(PYP.CITY));
						if(!TextUtils.isEmpty(city)){
							JSONArray city_values = pyps.optJSONArray(city);
							
							if(city_values!=null){
								//Update item on DB with values from JSONObject
								Utils.updateCity(cr,c.getLong(c.getColumnIndex(PYP._ID)),city_values);
								//Remove item from JSONObject
								pyps.remove(city);
								Log.d(TAG,"Removing "+city+" from jsonObject ");
								Log.d(TAG,"jsonObject "+pyps.toString());
							}
						}
					}while(c.moveToNext());
				}
			} finally{
				c.close();
			}
		}
		
		if(pyps.length() > 0){
			//Insert remaining cities
			Log.d(TAG,"Insert remaining cities ");
			Log.d(TAG,"jsonObject "+pyps.toString());
			Utils.insertCities(cr,pyps);
		}
	}
		
}
